package edu.ccit.shudong.controller;

import edu.ccit.shudong.dto.*;
import edu.ccit.shudong.service.IUserService;
import edu.ccit.shudong.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Suting Luo
 * @since 2024-06-14
 */
@RestController
@RequestMapping("/users")
@Api(tags = "用户")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT})
public class UserController {
    @Autowired
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Object register(@RequestBody UserRegisterDTO userRegisterDTO) {
//        if (!ReUtil.isMatch("^[a-z][a-z0-9]{2,29}$", userRegisterDTO.getUsername())) return R.error("用户名不符合要求");
//        if (!ReUtil.isMatch("^.{6,15}$", userRegisterDTO.getPassword())) return R.error("密码不符合要求");
//        if (!Validator.isEmail(userRegisterDTO.getEmail())) return R.error("邮箱格式非法");
//        if (!Validator.isMobile(userRegisterDTO.getPhone())) return R.error("电话非法");
//        if (!Validator.isBirthday(userRegisterDTO.getBirthday())) return R.error("生日非法");

        boolean flag = userService.register(userRegisterDTO);
        return flag ? R.ok("用户注册成功") : R.error("用户注册失败");
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Object login(@RequestBody UserLoginDTO userLoginDTO) {
        String token = userService.login(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        if (token == null || token.isEmpty()) return R.error("用户名或密码错误");
        TokenDTO tokenDTO = new TokenDTO();
        tokenDTO.setToken(token);
        return R.ok("登录成功", tokenDTO);
    }

    @ApiOperation("用户详情")
    @GetMapping("/profile")
    public Object profile(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        UserProfileDTO user = userService.getProfileByToken(token);
        return user != null ? R.ok("用户详情获取成功", user) : R.error("用户详情获取失败");
    }

    @ApiOperation("密码重置")
    @PutMapping("/password")
    public Object resetPassword(HttpServletRequest request, UserPasswordResetDTO passwordResetDTO) {
        String token = request.getHeader("Authorization");
//        if (!ReUtil.isMatch("^.{6,15}$", passwordResetDTO.getNewPassword())) return R.error("密码不符合要求");
        boolean flag = userService.resetPassword(token, passwordResetDTO);
        return flag ? R.ok("密码重置成功") : R.error("密码重置失败");
    }
}
